package com.wanlink.mall.base;

import android.content.Context;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.reactivex.disposables.Disposable;

/**
 * @user chenqm
 * @desc BasePresenter
 */

public abstract class BasePresenter<V> {

    protected Reference<V> mViewRef;

    public Context getContext() {
        if (!isViewAttached()) {
            return null;
        }
        if (mViewRef.get() instanceof BActivity) {
            return ((BActivity) mViewRef.get()).mContext;
        }
        if (mViewRef.get() instanceof BFragment) {
            return ((BFragment) mViewRef.get()).mContext;
        }
        return null;

    }

    public void attachView(V view) {
        mViewRef = new WeakReference<V>(view);
    }

    protected V getView() {
        return mViewRef.get();
    }

    public boolean isViewAttached() {
        return mViewRef != null && mViewRef.get() != null;
    }

    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
        dispose();
    }

    //    统一管理所有的订阅生命周期
    public void addDisposable(Disposable disposable) {
        if (!isViewAttached()) {
            return;
        }
        if (mViewRef.get() instanceof BActivity) {
            ((BActivity) mViewRef.get()).addDisposable(disposable);
        }
        if (mViewRef.get() instanceof BFragment) {
            ((BFragment) mViewRef.get()).addDisposable(disposable);
        }
    }

    public void dispose() {
        if (!isViewAttached()) {
            return;
        }
        if (mViewRef.get() instanceof BActivity) {
            ((BActivity) mViewRef.get()).dispose();
        }else if (mViewRef.get() instanceof BFragment) {
            ((BFragment) mViewRef.get()).dispose();
        }
    }

}
